//
//  DownloadTaskTool.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/3/25.
//

import UIKit

class DownloadTaskTool: NSObject, URLSessionDownloadDelegate {
    
    //文件资源地址
    var downUrl:String = ""
    //保存路径
    var savePath:String = ""
    
    //下载进度回调
    var progressBlock: ((Float) -> ())?
    
    var currentSession:URLSession?
    var downloadTask:URLSessionDownloadTask?
    
    var downloadData:Data = Data()//下载的数据
    
    override init() {
        super.init()
        let config = URLSessionConfiguration.default
        currentSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
    }
    
    //MARK:启动断点续传下载请求
    func start() {
        if downloadData.count > 0 {
            self.downloadTask = currentSession?.downloadTask(withResumeData: downloadData)
            self.downloadTask?.resume()
        } else {
            if let Url = URL(string: self.downUrl) {
                let request = URLRequest(url: Url)
                self.downloadTask = currentSession?.downloadTask(with: request)
                self.downloadTask?.resume()
            }
        }
    }
    
    //MARK:取消断点续传下载请求
    func cancel() {
        self.downloadTask?.cancel(byProducingResumeData: { resumeData in
            print(resumeData?.count)
            if resumeData != nil {
                self.downloadData = resumeData!
            }
        })
    }
    
    
    //下载代理方法，下载结束
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //保存文件
        if !savePath.isEmpty {
            //location位置转换
            let locationPath = location.path
            //移除旧文件
            if FileManager.default.fileExists(atPath: savePath) {
                do {
                    try FileManager.default.removeItem(atPath: savePath)
                } catch {
                    print(error)
                }
            }
            //生成新文件
            if !FileManager.default.fileExists(atPath: savePath) {
                do {
                    try FileManager.default.moveItem(atPath: locationPath, toPath: savePath)
                } catch {
                    print(error)
                }
            }
        }
    }
    
    //下载代理方法，监听下载进度
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        //获取进度
        let written = (Float)(totalBytesWritten)
        let total = (Float)(totalBytesExpectedToWrite)
        let pro = written/total
        if let onProgress = progressBlock {
            onProgress(pro)
        }
    }
    
    //下载代理方法，下载偏移
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        //下载偏移，主要用于暂停续传
    }
    
}
